<script setup lang="ts">
import { reactive, computed } from 'vue'
import { ElButton, ElForm, ElRow, ElInput, ElInputNumber, ElSelect, ElOption } from 'element-plus'
// import dayjs from 'dayjs'
import { useRouter, useRoute } from 'vue-router'
import {
  createAppParameterNamesApi,
  updateAppParameterNamesApi,
  getAppParameterNamesDetailApi
} from '@/api/app-parameter-name'
import { AppParameterName } from '@/api/app-parameter-name/types'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { FormItem } from '@/components/Form'
import { useValidator } from '@/hooks/web/useValidator'
import { useCreate } from '@/hooks/web/useCreate'
import { onMounted } from 'vue'

const { push } = useRouter()

const back = () => {
  push('/system/app-parameter-name')
}

const { required } = useValidator()

const instance: AppParameterName = reactive(new AppParameterName())
const route = useRoute()

const { elFormRef, openMode, save, loading } = useCreate({
  instance,
  route,
  afterSave: back,
  createApi: createAppParameterNamesApi,
  updateApi: updateAppParameterNamesApi
})

const rules = reactive({
  id: [required('请填写代码')],
  name: [required('请填写名称')],
  description: [required('请填写描述')],
  level: [required()],
  sequence: [required()]
})

const title = computed(() => {
  return openMode.value === 'CREATE' ? '添加参数模板' : '编辑参数模板'
})

onMounted(async () => {
  if (openMode.value === 'UPDATE') {
    const { data } = await getAppParameterNamesDetailApi(route.params.id as string)
    instance.init(data)
  }
})
</script>

<template>
  <ContentDetailWrap :title="title" @back="back">
    <template #right>
      <ElButton type="primary" :loading="loading" @click="save"> 保存 </ElButton>
    </template>

    <ElForm ref="elFormRef" :model="instance" label-width="100px" :rules="rules">
      <ElRow style="max-width: 450px; margin: 0 auto">
        <FormItem :col-props="{ span: 24 }" label="代码" prop="id">
          <ElInput v-model="instance.id" maxlength="50" :disabled="openMode === 'UPDATE'" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="名称" prop="name">
          <ElInput v-model="instance.name" maxlength="200" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="描述" prop="description">
          <ElInput type="textarea" v-model="instance.description" :rows="3" />
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="可见范围" prop="level">
          <ElSelect v-model="instance.level">
            <ElOption
              v-for="item of ['Hotel', 'Platform']"
              :key="item"
              :value="item"
              :label="item"
            />
          </ElSelect>
        </FormItem>

        <FormItem :col-props="{ span: 24 }" label="序号" prop="sequence">
          <ElInputNumber v-model="instance.sequence" controls-position="right" :min="1" />
        </FormItem>
      </ElRow>
    </ElForm>
  </ContentDetailWrap>
</template>
